package com.tianqicode.spring.beans.factory.support;

import com.tianqicode.spring.beans.BeansException;
import com.tianqicode.spring.beans.factory.config.BeanDefinition;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;

import java.lang.reflect.Constructor;

/**
 * 使用Cglib构造bean
 */
public class CglibSubclassingInstantiationStrategy extends SimpleInstantiationStrategy {

    private static class CglibSubclassCreator {
        public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) throws BeansException {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(beanDefinition.getBeanClass());
            enhancer.setCallback(new NoOp() {
                @Override
                public int hashCode() {
                    return super.hashCode();
                }
            });
            if (null == ctor) return enhancer.create();
            return enhancer.create(ctor.getParameterTypes(), args);
        }
    }
}
